import { Component, OnInit } from '@angular/core';
import { ActivatedRoute } from '@angular/router';
import { HttpResponse, HttpErrorResponse } from '@angular/common/http';
import { Observable } from 'rxjs';
import * as moment from 'moment';
import { DATE_TIME_FORMAT } from 'app/shared/constants/input.constants';

import { IDeliverOffer } from 'app/shared/model/deliver-offer.model';
import { DeliverOfferService } from './deliver-offer.service';

@Component({
    selector: 'app-deliver-offer-update',
    templateUrl: './deliver-offer-update.component.html'
})
export class DeliverOfferUpdateComponent implements OnInit {
    private _deliverOffer: IDeliverOffer;
    isSaving: boolean;
    leaveDate: string;
    arriveDate: string;
    createdDate: string;

    constructor(private deliverOfferService: DeliverOfferService, private activatedRoute: ActivatedRoute) {}

    ngOnInit() {
        this.isSaving = false;
        this.activatedRoute.data.subscribe(({ deliverOffer }) => {
            this.deliverOffer = deliverOffer;
        });
    }

    previousState() {
        window.history.back();
    }

    save() {
        this.isSaving = true;
        this.deliverOffer.leaveDate = moment(this.leaveDate, DATE_TIME_FORMAT);
        this.deliverOffer.arriveDate = moment(this.arriveDate, DATE_TIME_FORMAT);
        this.deliverOffer.createdDate = moment(this.createdDate, DATE_TIME_FORMAT);
        if (this.deliverOffer.id !== undefined) {
            this.subscribeToSaveResponse(this.deliverOfferService.update(this.deliverOffer));
        } else {
            this.subscribeToSaveResponse(this.deliverOfferService.create(this.deliverOffer));
        }
    }

    private subscribeToSaveResponse(result: Observable<HttpResponse<IDeliverOffer>>) {
        result.subscribe((res: HttpResponse<IDeliverOffer>) => this.onSaveSuccess(), (res: HttpErrorResponse) => this.onSaveError());
    }

    private onSaveSuccess() {
        this.isSaving = false;
        this.previousState();
    }

    private onSaveError() {
        this.isSaving = false;
    }
    get deliverOffer() {
        return this._deliverOffer;
    }

    set deliverOffer(deliverOffer: IDeliverOffer) {
        this._deliverOffer = deliverOffer;
        this.leaveDate = moment(deliverOffer.leaveDate).format(DATE_TIME_FORMAT);
        this.arriveDate = moment(deliverOffer.arriveDate).format(DATE_TIME_FORMAT);
        this.createdDate = moment(deliverOffer.createdDate).format(DATE_TIME_FORMAT);
    }
}
